import UIKit
import Flutter
import BMPlayer
import SnapKit
import SwiftyJSON

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
    let typeName = "nativetype"
    let pluginName = "nativepluginName"
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    
    //----------
    var count = 100
    if let controller: FlutterViewController = window.rootViewController as? FlutterViewController {
        
        
        let messageChannel = FlutterBasicMessageChannel(name: "bbbb", binaryMessenger: controller.binaryMessenger)
        messageChannel.sendMessage("hello")
        messageChannel.setMessageHandler { message, reply in
            print("msg:\(message)")
            reply("reply copy")
            messageChannel.sendMessage("hello again")
        }
        
        let channel = FlutterMethodChannel(name: "samples.flutter.dev/battery", binaryMessenger: controller.binaryMessenger)
        channel.setMethodCallHandler { call, result in
            messageChannel.sendMessage("hello again++")
            print("method \(call.method)")
            count += 10
            result(count)
            
        }
        
        
//        cn.setMessageHandler { call, result in
//            print("FlutterMethodChannel")
//            result("fuckyou")
//            let msg = ["aaa":"bbb"]
//            SwiftyJSON
//            let mmm = JSON.init(msg)
//            print("\(mmm.string)")
//            cn.sendMessage("") { resp in
//                if let resp = resp {
//                    print("resp:\(resp)")
//                }else{
//                    print("no resp")
//                }
//            }
//        }
//        channel.sendm
    }
    
    
    GeneratedPluginRegistrant.register(with: self)
    weak var registrar = self.registrar(forPlugin: "plugin-name")
    let factory = FLNativeViewFactory(messenger: registrar!.messenger())
    self.registrar(forPlugin: "<plugin-name>")!.register(factory, withId: "nativeType")
    
    
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}


class FLNativeViewFactory: NSObject, FlutterPlatformViewFactory {
    private var messenger: FlutterBinaryMessenger
    init(messenger: FlutterBinaryMessenger) {
        self.messenger = messenger
        super.init()
    }

    func create(
        withFrame frame: CGRect,
        viewIdentifier viewId: Int64,
        arguments args: Any?
    ) -> FlutterPlatformView {
        return FLNativeView(
            frame: frame,
            viewIdentifier: viewId,
            arguments: args,
            binaryMessenger: messenger)
    }
}

class FLNativeView: NSObject, FlutterPlatformView {
    private var _view: UIView

    init(
        frame: CGRect,
        viewIdentifier viewId: Int64,
        arguments args: Any?,
        binaryMessenger messenger: FlutterBinaryMessenger?
    ) {
        _view = UIView()
        super.init()
        // iOS views can be created here
        createNativeView(view: _view)
        if let args = args as? [String: Any]{
            print("arguments\(args["sss"])")
        }else{
            print("no arg")
        }
        print("?\(messenger==nil)")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10) {
            let data = "hellomsg".data(using: String.Encoding.utf8)
            messenger?.send(onChannel: "bbbb", message: data)
            print("sended")
        }
    }

    func view() -> UIView {
        return _view
    }

    func createNativeView(view _view: UIView){
        print("vv \(_view.frame)")
        _view.backgroundColor = UIColor.blue
        let nativeLabel = UILabel()
        nativeLabel.text = "Native text from iOS"
        nativeLabel.textColor = UIColor.white
        nativeLabel.textAlignment = .center
        nativeLabel.frame = CGRect(x: 0, y: 0, width: 180, height: 48.0)
//        nativeLabel.
        _view.addSubview(nativeLabel)
        
        let pv = BMPlayerControlView()
        let player = BMPlayer(customControllView: pv)
        _view.addSubview(player)
        player.snp.makeConstraints { (maker) in
            maker.left.right.top.bottom.equalToSuperview()
//            maker.bottom.equalToSuperview().offset(-30)
        }
        let asset = BMPlayerResource(url: URL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!,
                                     name: "")
        player.setVideo(resource: asset)
//        player.play()
        player.pause()
    }
}


class FLPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let factory = FLNativeViewFactory(messenger: registrar.messenger())
        registrar.register(factory, withId: "nativeType")
        print("register plugin")
    }
}



extension AppDelegate {
    func addMsg(){
        
    }
}
